import { Component, OnInit, Input, ViewEncapsulation, AfterViewInit } from '@angular/core';
import { DanmakuMessage } from '../../../danmaku.def';
import { BiliwsService } from '../../../biliws.service';

@Component({
  selector: 'yt-live-chat-text-message-renderer',
  templateUrl: './message.component.html',
  styleUrls: ['./message.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class MessageComponent implements OnInit , AfterViewInit {

  @Input() item: DanmakuMessage;

  constructor(private bili: BiliwsService) { }

  ngOnInit() {
  }

  getType() {
    if (this.item.uid === this.bili.ownerId) {
      return 'owner';
    } else if (this.item.is_admin) {
      return 'moderator';
    } else if (this.item.guard > 0) {
      return 'member';
    }
    return null;
  }

  getIcon() {
    if (this.item.guard === 3) {
      return '';
    } else if (this.item.guard === 2) {
      return '';
    } else if (this.item.guard === 1) {
      return '';
    } else {
      return '';
    }
  }
  ngAfterViewInit() {
    // if (!isPlatformBrowser(this.plat)) {
      // return;
    // }
    // document.documentElement.scrollTop=document.documentElement.scrollHeight;
    window.scrollTo(0, document.documentElement.scrollHeight);
  }

  getRepeatGradientColor() {
    return this.getColorGradient('#2196f3', '#ff5722', this.item.repeat > 10 ? 1 : this.item.repeat / 10.0);
  }

  getColorGradient(start_color, end_color, percent) {
    // strip the leading # if it's there
    start_color = start_color.replace(/^\s*#|\s*$/g, '');
    end_color = end_color.replace(/^\s*#|\s*$/g, '');

    // convert 3 char codes --> 6, e.g. `E0F` --> `EE00FF`
    if (start_color.length === 3) {
      start_color = start_color.replace(/(.)/g, '$1$1');
    }

    if (end_color.length === 3) {
      end_color = end_color.replace(/(.)/g, '$1$1');
    }

    // get colors
    const start_red = parseInt(start_color.substr(0, 2), 16),
        start_green = parseInt(start_color.substr(2, 2), 16),
        start_blue = parseInt(start_color.substr(4, 2), 16);

    const end_red = parseInt(end_color.substr(0, 2), 16),
        end_green = parseInt(end_color.substr(2, 2), 16),
        end_blue = parseInt(end_color.substr(4, 2), 16);

    // calculate new color
    const diff_red_ = end_red - start_red;
    const diff_green_ = end_green - start_green;
    const diff_blue_ = end_blue - start_blue;

    let diff_red = ( (diff_red_ * percent) + start_red ).toString(16).split('.')[0];
    let diff_green = ( (diff_green_ * percent) + start_green ).toString(16).split('.')[0];
    let diff_blue = ( (diff_blue_ * percent) + start_blue ).toString(16).split('.')[0];

    // ensure 2 digits by color
    if ( diff_red.length === 1 ) { diff_red = '0' + diff_red; }
    if ( diff_green.length === 1 ) { diff_green = '0' + diff_green; }
    if ( diff_blue.length === 1 ) { diff_blue = '0' + diff_blue; }

    return '#' + diff_red + diff_green + diff_blue;
  }
}
